<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>操作日志 - 商品管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .status-success {
            color: #28a745;
        }
        .status-error {
            color: #dc3545;
        }
        .log-detail {
            max-width: 300px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .table-responsive {
            max-height: calc(100vh - 250px);
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="/dashboard">商品管理系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/dashboard">
                            <i class="bi bi-speedometer2"></i> 仪表盘
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/product/list">
                            <i class="bi bi-box"></i> 商品管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/category/list">
                            <i class="bi bi-tags"></i> 分类管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/log/list">
                            <i class="bi bi-clock-history"></i> 操作日志
                        </a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle"></i> <span th:text="${session.currentUser?.username}">管理员</span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/auth/profile">个人资料</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="/auth/logout">退出登录</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">
                            <i class="bi bi-clock-history"></i> 操作日志
                        </h5>
                        <div>
                            <button class="btn btn-outline-primary btn-sm" id="statisticsBtn">
                                <i class="bi bi-bar-chart"></i> 统计分析
                            </button>
                            <button class="btn btn-outline-success btn-sm" id="exportBtn">
                                <i class="bi bi-download"></i> 导出
                            </button>
                            <button class="btn btn-outline-danger btn-sm" id="cleanBtn">
                                <i class="bi bi-trash"></i> 清理
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <!-- 搜索表单 -->
                        <form id="searchForm" class="row g-3 mb-3">
                            <div class="col-md-2">
                                <label for="operationType" class="form-label">操作类型</label>
                                <select class="form-select form-select-sm" id="operationType" name="operationType">
                                    <option value="">全部</option>
                                    <option value="CREATE">新增</option>
                                    <option value="UPDATE">更新</option>
                                    <option value="DELETE">删除</option>
                                    <option value="QUERY">查询</option>
                                    <option value="LOGIN">登录</option>
                                    <option value="LOGOUT">登出</option>
                                    <option value="EXPORT">导出</option>
                                    <option value="IMPORT">导入</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="module" class="form-label">操作模块</label>
                                <select class="form-select form-select-sm" id="module" name="module">
                                    <option value="">全部</option>
                                    <option value="商品管理">商品管理</option>
                                    <option value="分类管理">分类管理</option>
                                    <option value="用户管理">用户管理</option>
                                    <option value="仪表盘">仪表盘</option>
                                    <option value="认证授权">认证授权</option>
                                    <option value="系统管理">系统管理</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="status" class="form-label">操作状态</label>
                                <select class="form-select form-select-sm" id="status" name="status">
                                    <option value="">全部</option>
                                    <option value="SUCCESS">成功</option>
                                    <option value="ERROR">失败</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="startTime" class="form-label">开始时间</label>
                                <input type="datetime-local" class="form-control form-control-sm" id="startTime" name="startTime">
                            </div>
                            <div class="col-md-2">
                                <label for="endTime" class="form-label">结束时间</label>
                                <input type="datetime-local" class="form-control form-control-sm" id="endTime" name="endTime">
                            </div>
                            <div class="col-md-2">
                                <label for="keyword" class="form-label">关键字</label>
                                <input type="text" class="form-control form-control-sm" id="keyword" name="keyword" placeholder="描述/模块/用户名">
                            </div>
                            <div class="col-12">
                                <button type="button" class="btn btn-primary btn-sm" id="searchBtn">
                                    <i class="bi bi-search"></i> 搜索
                                </button>
                                <button type="button" class="btn btn-secondary btn-sm" id="resetBtn">
                                    <i class="bi bi-arrow-clockwise"></i> 重置
                                </button>
                                <button type="button" class="btn btn-danger btn-sm" id="batchDeleteBtn" disabled>
                                    <i class="bi bi-trash"></i> 批量删除
                                </button>
                            </div>
                        </form>

                        <!-- 数据表格 -->
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead class="table-light sticky-top">
                                    <tr>
                                        <th width="40">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="selectAll">
                                            </div>
                                        </th>
                                        <th>用户名</th>
                                        <th>操作类型</th>
                                        <th>模块</th>
                                        <th>描述</th>
                                        <th>请求URL</th>
                                        <th>IP地址</th>
                                        <th>状态</th>
                                        <th>执行时间</th>
                                        <th>操作时间</th>
                                        <th width="100">操作</th>
                                    </tr>
                                </thead>
                                <tbody id="logTableBody">
                                    <!-- 数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>

                        <!-- 分页 -->
                        <nav aria-label="Page navigation" class="mt-3">
                            <ul class="pagination justify-content-center" id="pagination">
                                <!-- 分页将通过JavaScript动态生成 -->
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 日志详情模态框 -->
    <div class="modal fade" id="logDetailModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">操作日志详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <strong>日志ID：</strong>
                            <span id="detailId"></span>
                        </div>
                        <div class="col-md-6">
                            <strong>用户名：</strong>
                            <span id="detailUsername"></span>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <strong>操作类型：</strong>
                            <span id="detailOperationType"></span>
                        </div>
                        <div class="col-md-6">
                            <strong>操作模块：</strong>
                            <span id="detailModule"></span>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-12">
                            <strong>操作描述：</strong>
                            <span id="detailDescription"></span>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <strong>请求URL：</strong>
                            <span id="detailRequestUrl"></span>
                        </div>
                        <div class="col-md-6">
                            <strong>请求方法：</strong>
                            <span id="detailRequestMethod"></span>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <strong>IP地址：</strong>
                            <span id="detailIpAddress"></span>
                        </div>
                        <div class="col-md-6">
                            <strong>操作状态：</strong>
                            <span id="detailStatus"></span>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-12">
                            <strong>请求参数：</strong>
                            <pre id="detailRequestParams" class="bg-light p-2 rounded"></pre>
                        </div>
                    </div>
                    <div class="row mb-3" id="errorRow" style="display: none;">
                        <div class="col-md-12">
                            <strong>错误信息：</strong>
                            <pre id="detailErrorMessage" class="bg-danger bg-opacity-10 text-danger p-2 rounded"></pre>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <strong>执行时间：</strong>
                            <span id="detailExecutionTime"></span> ms
                        </div>
                        <div class="col-md-6">
                            <strong>操作时间：</strong>
                            <span id="detailCreatedAt"></span>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 统计分析模态框 -->
    <div class="modal fade" id="statisticsModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">操作日志统计分析</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="statStartTime" class="form-label">开始时间</label>
                            <input type="datetime-local" class="form-control" id="statStartTime">
                        </div>
                        <div class="col-md-6">
                            <label for="statEndTime" class="form-label">结束时间</label>
                            <input type="datetime-local" class="form-control" id="statEndTime">
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-12 text-center">
                            <button type="button" class="btn btn-primary" id="loadStatisticsBtn">加载统计</button>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">操作类型统计</div>
                                <div class="card-body">
                                    <canvas id="operationTypeChart"></canvas>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">模块操作统计</div>
                                <div class="card-body">
                                    <canvas id="moduleChart"></canvas>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">用户操作统计</div>
                                <div class="card-body">
                                    <canvas id="userChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 清理日志模态框 -->
    <div class="modal fade" id="cleanModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">清理操作日志</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="cleanDays" class="form-label">清理多少天前的日志</label>
                        <input type="number" class="form-control" id="cleanDays" min="1" value="30">
                        <div class="form-text">将清理指定天数之前的所有操作日志，此操作不可恢复</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmCleanBtn">确认清理</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script th:inline="javascript">
        // 全局变量
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 0;
        let selectedIds = [];

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 设置默认时间范围（最近7天）
            const now = new Date();
            const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
            
            document.getElementById('endTime').value = formatDateTimeLocal(now);
            document.getElementById('startTime').value = formatDateTimeLocal(sevenDaysAgo);
            
            // 加载数据
            loadLogs();
            
            // 绑定事件
            bindEvents();
        });

        // 格式化日期时间为datetime-local格式
        function formatDateTimeLocal(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            return `${year}-${month}-${day}T${hours}:${minutes}`;
        }

        // 绑定事件
        function bindEvents() {
            // 搜索按钮
            document.getElementById('searchBtn').addEventListener('click', function() {
                currentPage = 1;
                loadLogs();
            });
            
            // 重置按钮
            document.getElementById('resetBtn').addEventListener('click', function() {
                document.getElementById('searchForm').reset();
                
                // 设置默认时间范围
                const now = new Date();
                const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
                
                document.getElementById('endTime').value = formatDateTimeLocal(now);
                document.getElementById('startTime').value = formatDateTimeLocal(sevenDaysAgo);
                
                currentPage = 1;
                loadLogs();
            });
            
            // 全选复选框
            document.getElementById('selectAll').addEventListener('change', function() {
                const checkboxes = document.querySelectorAll('#logTableBody input[type="checkbox"]');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
                
                updateSelectedIds();
                updateBatchDeleteButton();
            });
            
            // 批量删除按钮
            document.getElementById('batchDeleteBtn').addEventListener('click', function() {
                if (selectedIds.length === 0) {
                    return;
                }
                
                if (confirm(`确定要删除选中的 ${selectedIds.length} 条记录吗？`)) {
                    batchDelete();
                }
            });
            
            // 导出按钮
            document.getElementById('exportBtn').addEventListener('click', function() {
                exportLogs();
            });
            
            // 清理按钮
            document.getElementById('cleanBtn').addEventListener('click', function() {
                const modal = new bootstrap.Modal(document.getElementById('cleanModal'));
                modal.show();
            });
            
            // 确认清理按钮
            document.getElementById('confirmCleanBtn').addEventListener('click', function() {
                const days = document.getElementById('cleanDays').value;
                if (days && days > 0) {
                    cleanLogs(days);
                }
            });
            
            // 统计分析按钮
            document.getElementById('statisticsBtn').addEventListener('click', function() {
                const modal = new bootstrap.Modal(document.getElementById('statisticsModal'));
                modal.show();
                
                // 设置默认时间范围
                const now = new Date();
                const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
                
                document.getElementById('statEndTime').value = formatDateTimeLocal(now);
                document.getElementById('statStartTime').value = formatDateTimeLocal(sevenDaysAgo);
            });
            
            // 加载统计按钮
            document.getElementById('loadStatisticsBtn').addEventListener('click', function() {
                loadStatistics();
            });
        }

        // 加载日志数据
        function loadLogs() {
            // 获取搜索条件
            const operationType = document.getElementById('operationType').value;
            const module = document.getElementById('module').value;
            const status = document.getElementById('status').value;
            const startTime = document.getElementById('startTime').value;
            const endTime = document.getElementById('endTime').value;
            const keyword = document.getElementById('keyword').value;
            
            // 构建请求参数
            const params = new URLSearchParams({
                pageNum: currentPage,
                pageSize: pageSize,
                operationType: operationType,
                module: module,
                status: status,
                startTime: startTime,
                endTime: endTime,
                keyword: keyword
            });
            
            // 发送请求
            fetch(`/log/page?${params}`)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        renderLogTable(data.data.list);
                        renderPagination(data.data.pages);
                        totalPages = data.data.pages;
                    } else {
                        alert(data.message || '加载数据失败');
                    }
                })
                .catch(error => {
                    console.error('加载数据失败:', error);
                    alert('加载数据失败');
                });
        }

        // 渲染日志表格
        function renderLogTable(logs) {
            const tbody = document.getElementById('logTableBody');
            tbody.innerHTML = '';
            
            if (logs.length === 0) {
                tbody.innerHTML = '<tr><td colspan="11" class="text-center">暂无数据</td></tr>';
                return;
            }
            
            logs.forEach(log => {
                const row = document.createElement('tr');
                
                // 状态样式
                const statusClass = log.status === 'SUCCESS' ? 'status-success' : 'status-error';
                const statusText = log.status === 'SUCCESS' ? '成功' : '失败';
                
                // 操作类型文本
                const operationTypeText = getOperationTypeText(log.operationType);
                
                row.innerHTML = `
                    <td>
                        <div class="form-check">
                            <input class="form-check-input log-checkbox" type="checkbox" value="${log.id}">
                        </div>
                    </td>
                    <td>${log.username || '-'}</td>
                    <td>${operationTypeText}</td>
                    <td>${log.module || '-'}</td>
                    <td class="log-detail" title="${log.description || '-'}">${log.description || '-'}</td>
                    <td class="log-detail" title="${log.requestUrl || '-'}">${log.requestUrl || '-'}</td>
                    <td>${log.ipAddress || '-'}</td>
                    <td class="${statusClass}">${statusText}</td>
                    <td>${log.executionTime || '-'}</td>
                    <td>${formatDateTime(log.createdAt)}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-info view-btn" data-id="${log.id}">
                            <i class="bi bi-eye"></i>
                        </button>
                    </td>
                `;
                
                tbody.appendChild(row);
            });
            
            // 绑定查看按钮事件
            document.querySelectorAll('.view-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const id = this.getAttribute('data-id');
                    viewLogDetail(id);
                });
            });
            
            // 绑定复选框事件
            document.querySelectorAll('.log-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    updateSelectedIds();
                    updateBatchDeleteButton();
                    updateSelectAllCheckbox();
                });
            });
        }

        // 渲染分页
        function renderPagination(pages) {
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';
            
            if (pages <= 1) {
                return;
            }
            
            // 上一页
            const prevLi = document.createElement('li');
            prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
            prevLi.innerHTML = `<a class="page-link" href="#" data-page="${currentPage - 1}">上一页</a>`;
            pagination.appendChild(prevLi);
            
            // 页码
            for (let i = 1; i <= pages; i++) {
                const li = document.createElement('li');
                li.className = `page-item ${i === currentPage ? 'active' : ''}`;
                li.innerHTML = `<a class="page-link" href="#" data-page="${i}">${i}</a>`;
                pagination.appendChild(li);
            }
            
            // 下一页
            const nextLi = document.createElement('li');
            nextLi.className = `page-item ${currentPage === pages ? 'disabled' : ''}`;
            nextLi.innerHTML = `<a class="page-link" href="#" data-page="${currentPage + 1}">下一页</a>`;
            pagination.appendChild(nextLi);
            
            // 绑定分页点击事件
            document.querySelectorAll('.page-link').forEach(link => {
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    const page = parseInt(this.getAttribute('data-page'));
                    if (page && page !== currentPage && page > 0 && page <= pages) {
                        currentPage = page;
                        loadLogs();
                    }
                });
            });
        }

        // 更新选中的ID
        function updateSelectedIds() {
            selectedIds = [];
            document.querySelectorAll('.log-checkbox:checked').forEach(checkbox => {
                selectedIds.push(checkbox.value);
            });
        }

        // 更新批量删除按钮状态
        function updateBatchDeleteButton() {
            const btn = document.getElementById('batchDeleteBtn');
            btn.disabled = selectedIds.length === 0;
        }

        // 更新全选复选框状态
        function updateSelectAllCheckbox() {
            const selectAll = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('.log-checkbox');
            const checkedBoxes = document.querySelectorAll('.log-checkbox:checked');
            
            if (checkboxes.length === 0) {
                selectAll.checked = false;
                selectAll.indeterminate = false;
            } else if (checkedBoxes.length === 0) {
                selectAll.checked = false;
                selectAll.indeterminate = false;
            } else if (checkedBoxes.length === checkboxes.length) {
                selectAll.checked = true;
                selectAll.indeterminate = false;
            } else {
                selectAll.checked = false;
                selectAll.indeterminate = true;
            }
        }

        // 查看日志详情
        function viewLogDetail(id) {
            fetch(`/log/${id}`)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        const log = data.data;
                        
                        // 填充详情数据
                        document.getElementById('detailId').textContent = log.id || '-';
                        document.getElementById('detailUsername').textContent = log.username || '-';
                        document.getElementById('detailOperationType').textContent = getOperationTypeText(log.operationType);
                        document.getElementById('detailModule').textContent = log.module || '-';
                        document.getElementById('detailDescription').textContent = log.description || '-';
                        document.getElementById('detailRequestUrl').textContent = log.requestUrl || '-';
                        document.getElementById('detailRequestMethod').textContent = log.requestMethod || '-';
                        document.getElementById('detailIpAddress').textContent = log.ipAddress || '-';
                        document.getElementById('detailStatus').textContent = log.status === 'SUCCESS' ? '成功' : '失败';
                        document.getElementById('detailRequestParams').textContent = log.requestParams || '-';
                        document.getElementById('detailExecutionTime').textContent = log.executionTime || '-';
                        document.getElementById('detailCreatedAt').textContent = formatDateTime(log.createdAt);
                        
                        // 显示或隐藏错误信息
                        if (log.errorMessage) {
                            document.getElementById('errorRow').style.display = 'block';
                            document.getElementById('detailErrorMessage').textContent = log.errorMessage;
                        } else {
                            document.getElementById('errorRow').style.display = 'none';
                        }
                        
                        // 显示模态框
                        const modal = new bootstrap.Modal(document.getElementById('logDetailModal'));
                        modal.show();
                    } else {
                        alert(data.message || '获取详情失败');
                    }
                })
                .catch(error => {
                    console.error('获取详情失败:', error);
                    alert('获取详情失败');
                });
        }

        // 批量删除
        function batchDelete() {
            fetch('/log/batch', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(selectedIds)
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        alert('批量删除成功');
                        loadLogs();
                    } else {
                        alert(data.message || '批量删除失败');
                    }
                })
                .catch(error => {
                    console.error('批量删除失败:', error);
                    alert('批量删除失败');
                });
        }

        // 导出日志
        function exportLogs() {
            // 获取搜索条件
            const operationType = document.getElementById('operationType').value;
            const module = document.getElementById('module').value;
            const status = document.getElementById('status').value;
            const startTime = document.getElementById('startTime').value;
            const endTime = document.getElementById('endTime').value;
            const keyword = document.getElementById('keyword').value;
            
            // 构建请求参数
            const params = new URLSearchParams({
                operationType: operationType,
                module: module,
                status: status,
                startTime: startTime,
                endTime: endTime,
                keyword: keyword
            });
            
            // 下载文件
            window.location.href = `/log/export?${params}`;
        }

        // 清理日志
        function cleanLogs(days) {
            fetch(`/log/clean/${days}`, {
                method: 'DELETE'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        alert('清理成功');
                        bootstrap.Modal.getInstance(document.getElementById('cleanModal')).hide();
                        loadLogs();
                    } else {
                        alert(data.message || '清理失败');
                    }
                })
                .catch(error => {
                    console.error('清理失败:', error);
                    alert('清理失败');
                });
        }

        // 加载统计数据
        function loadStatistics() {
            const startTime = document.getElementById('statStartTime').value;
            const endTime = document.getElementById('statEndTime').value;
            
            // 构建请求参数
            const params = new URLSearchParams({
                startTime: startTime,
                endTime: endTime
            });
            
            // 发送请求
            fetch(`/log/statistics?${params}`)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        const stats = data.data;
                        
                        // 渲染操作类型统计图表
                        renderOperationTypeChart(stats.operationTypeStats);
                        
                        // 渲染模块统计图表
                        renderModuleChart(stats.moduleStats);
                        
                        // 渲染用户统计图表
                        renderUserChart(stats.userStats);
                    } else {
                        alert(data.message || '加载统计数据失败');
                    }
                })
                .catch(error => {
                    console.error('加载统计数据失败:', error);
                    alert('加载统计数据失败');
                });
        }

        // 渲染操作类型统计图表
        function renderOperationTypeChart(data) {
            const ctx = document.getElementById('operationTypeChart').getContext('2d');
            
            // 销毁已存在的图表
            if (window.operationTypeChart) {
                window.operationTypeChart.destroy();
            }
            
            // 准备数据
            const labels = data.map(item => getOperationTypeText(item.name));
            const values = data.map(item => item.value);
            
            // 创建图表
            window.operationTypeChart = new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: labels,
                    datasets: [{
                        data: values,
                        backgroundColor: [
                            '#FF6384',
                            '#36A2EB',
                            '#FFCE56',
                            '#4BC0C0',
                            '#9966FF',
                            '#FF9F40',
                            '#FF6384',
                            '#C9CBCF'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });
        }

        // 渲染模块统计图表
        function renderModuleChart(data) {
            const ctx = document.getElementById('moduleChart').getContext('2d');
            
            // 销毁已存在的图表
            if (window.moduleChart) {
                window.moduleChart.destroy();
            }
            
            // 准备数据
            const labels = data.map(item => item.name);
            const values = data.map(item => item.value);
            
            // 创建图表
            window.moduleChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: values,
                        backgroundColor: [
                            '#FF6384',
                            '#36A2EB',
                            '#FFCE56',
                            '#4BC0C0',
                            '#9966FF',
                            '#FF9F40'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });
        }

        // 渲染用户统计图表
        function renderUserChart(data) {
            const ctx = document.getElementById('userChart').getContext('2d');
            
            // 销毁已存在的图表
            if (window.userChart) {
                window.userChart.destroy();
            }
            
            // 准备数据
            const labels = data.map(item => item.name);
            const values = data.map(item => item.value);
            
            // 创建图表
            window.userChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: '操作次数',
                        data: values,
                        backgroundColor: '#36A2EB'
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });
        }

        // 获取操作类型文本
        function getOperationTypeText(type) {
            switch (type) {
                case 'CREATE': return '新增';
                case 'UPDATE': return '更新';
                case 'DELETE': return '删除';
                case 'QUERY': return '查询';
                case 'LOGIN': return '登录';
                case 'LOGOUT': return '登出';
                case 'EXPORT': return '导出';
                case 'IMPORT': return '导入';
                default: return type || '未知';
            }
        }

        // 格式化日期时间
        function formatDateTime(dateTime) {
            if (!dateTime) return '-';
            
            const date = new Date(dateTime);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
    </script>
</body>
</html>